package com.gcsoftware.Interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.gcsoftware.configs.AppConstants.Sys.SYS_SESSION_ID;

/**
 * 登陆拦截
 * @author czp
 * date 2018-05-28
 */
public class LoginInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String[] uris = {
      "/*/login*"
    };

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        String uri = httpServletRequest.getRequestURI();
        String sessionId = httpServletRequest.getSession().getId();
        String cacheSessionId = LoginCache.LOGIN_SESSION_ID.get(SYS_SESSION_ID.getValue());
        String path = httpServletRequest.getContextPath();
//        if (sessionId.equals(cacheSessionId) || uriFilter(uri)) {
//            return true;
//        } else {
//            httpServletResponse.sendRedirect(path + "/login");
//            return false;
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

    private boolean uriFilter(String uri) {
        for (String u : uris) {
            Pattern pattern = Pattern.compile(u);
            Matcher matcher = pattern.matcher(uri);
            if (matcher.find()) return true;
        }
        return false;
    }
}
